package main;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;

import protocol.HTTP;

public class MessagingServer implements Runnable {
	private char _delimiter;
	private int _port;
	private ServerConcurrencyModel _ServerConcurrencyModel;
	private Charset _charset;
	private boolean _shouldStop;
	private ServerSocket socket;

	public MessagingServer(char delimiter, int port, Charset charset,
			ServerConcurrencyModel serverConcurrencyModel) {
		_delimiter = delimiter;
		_port = port;
		_ServerConcurrencyModel = serverConcurrencyModel;
		_charset = charset;
		_shouldStop = false;

	}

	@Override
	public void run() {
		//  if (args.length != 1) {
		//     System.err.println("please supply only one argument, the port to bind.");
		//    return;
		//}
		/*The characteristic of the server concurrency model is determined by the selected implementation for the scm 
		instance (SingleThread, ThreadPerClient or ThreadPool - as described in the next sections)*/

		try {
			System.out.println("Started Server!");
			socket = new ServerSocket(_port);
			while (!_shouldStop) {
				Socket s = socket.accept();

				Tokenizer tokenizer = new MessageTokenizer(
						new InputStreamReader(s.getInputStream(), _charset),
						_delimiter);
				HTTP protocol = new HTTP();
				Runnable connectionHandler = new ConnectionHandler(s, _charset,
						tokenizer, protocol);
				_ServerConcurrencyModel.apply(connectionHandler);
			}
			stop();
		} catch (Exception e) {
		}

	}

	public void stop() {
		_shouldStop = true;
		try {
			this.socket.close();
			System.out.println("current socket killed");
		} catch (IOException e) {
			System.out.println("current socket killed");
		}
		_ServerConcurrencyModel.stop();
		System.out.println("killing server");
	}

}